package com.fengniu.ejb.dao.impl;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;

import com.fengniu.ejb.dao.TagLogDaoLocal;
import com.fengniu.ejb.dao.TagLogDaoRemote;
import com.fengniu.ejb.dao.interceptor.TracingInterceptor;
import com.fengniu.ejb.dao.util.DaoUtil;
import com.fengniu.ejb.dao.util.IEJBConstants;
import com.fengniu.ejb.entity.TagLog;

/**
 * @author conan
 * 
 */
@Stateless
@Local( { TagLogDaoLocal.class })
@LocalBinding(jndiBinding = IEJBConstants.TagLogDaoLocalJndiName)
@Remote( { TagLogDaoRemote.class })
@RemoteBinding(jndiBinding = IEJBConstants.TagLogDaoRemoteJndiName)
@Interceptors( { TracingInterceptor.class })
public class TagLogDaoImpl implements TagLogDaoLocal, TagLogDaoRemote {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3079041167627749965L;

	static Logger logger = Logger.getLogger(TagLogDaoImpl.class);

	@PersistenceContext(unitName = "default")
	protected EntityManager em;

	public List<TagLog> getListTagLog(Integer[] statusIds, int pgno, int pgsize, String orderBy) {
		Query q = this.getQueryTagLogBy( statusIds, orderBy, true);
		List result = DaoUtil.getResultList(q, pgno, pgsize);
		return result;
	}

	private Query getQueryTagLogBy(Integer[] statusIds, String orderBy, boolean isGetList) {

		String ent = isGetList ? "t" : "count(t)";

		String eql = "select " + ent + " from  TagLog t";
		String whereand = "";
		if (DaoUtil.isNull(statusIds) == false) {
			whereand = DaoUtil.getWhereOrAndStr(whereand);
			eql += whereand + "  t.status IN (:statusIds) ";
		}
		if (isGetList && orderBy != null && orderBy.trim() != "") {
			eql += " ORDER BY " + orderBy;
		}
		logger.debug("eql=[" + eql + "]");

		Query q = em.createQuery(eql);
		if (DaoUtil.isNull(statusIds) == false) {
			List rts = DaoUtil.getListFromArray(statusIds);
			q.setParameter("statusIds", rts);
		}

		return q;
	}

	public TagLog saveTagLog(TagLog tagLog) {
		return em.merge(tagLog);
	}
}
